<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="收费项目名称" prop="projectName">
        <el-input
            v-model="queryParams.projectName"
            placeholder="请输入收费项目名称"
            clearable
            @keyup.enter="handleQuery"
            style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="收费项目类型" prop="typeId">
        <el-select v-model="queryParams.typeId" placeholder="请选择收费项目类型" clearable @change="handleQuery"
                   style="width: 240px">
          <el-option
              v-for="item in typeList"
              :key="item.id"
              :label="item.typeName"
              :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="收费类型" prop="billingType">
        <el-select v-model="queryParams.billingType" placeholder="请选择收费类型" clearable style="width: 240px">
          <el-option
              v-for="dict in billing_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
        >导出
        </el-button>
      </el-col>
    </el-row>

    <!--    @selection-change="handleSelectionChange"
          <el-table-column type="selection" width="55" align="center"/>-->
    <el-table v-loading="loading" :data="chargedItemsList">
      <el-table-column label="序号" align="center" type="index" width="60"/>
      <el-table-column label="收费项目名称" align="center" prop="projectName"/>
      <el-table-column label="收费项目类型" align="center" prop="typeName"/>
      <el-table-column label="收费标准" align="center" prop="ifCheckInFee">
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true"/>
      <el-table-column label="创建人" align="center" prop="createBy" :show-overflow-tooltip="true"/>
      <el-table-column label="创建时间" align="center" prop="createTime" :show-overflow-tooltip="true"/>
      <el-table-column label="最后修改人" align="center" prop="updateBy" :show-overflow-tooltip="true"/>
      <el-table-column label="最后修改时间" align="center" prop="updateTime" :show-overflow-tooltip="true"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
              type="text"
              icon="Edit"
              @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button
              type="text"
              icon="Delete"
              @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改收费项目对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="chargedItemsRef" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="收费项目名称" prop="projectName">
          <el-input v-model="form.projectName" placeholder="请输入收费项目名称"/>
        </el-form-item>
        <el-form-item label="收费项目类型" prop="typeId">
          <el-select v-model="form.typeId" placeholder="请选择收费项目类型" @change="handleChange" clearable>
            <el-option
                v-for="item in typeList"
                :key="item.id"
                :label="item.typeName"
                :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否入住收费" prop="ifCheckInFee" v-if="billingType=='一次性收费'">
          <el-switch
              v-model="form.ifCheckInFee"
              active-value="1"
              inactive-value="0"/>
        </el-form-item>
        <el-form-item label="价格" prop="price" v-if="billingType=='一次性收费'">
          <el-input v-model="form.price" placeholder="请输入价格"/>
        </el-form-item>
        <el-form-item label="单位" prop="unit" v-if="billingType=='一次性收费'">
          <el-input v-model="form.unit" placeholder="请输入单位"/>
        </el-form-item>
        <el-form-item label="月收费标准/元" prop="monthlyFeeStandard" v-if="billingType=='月度收费'">
          <el-input v-model="form.monthlyFeeStandard" placeholder="请输入价格"/>
        </el-form-item>
        <el-form-item label="日收费标准/元" prop="dailyChargesStandard" v-if="billingType=='月度收费'">
          <el-input v-model="form.dailyChargesStandard" placeholder="请输入价格"/>
        </el-form-item>
        <el-form-item label="周期" prop="period" v-if="billingType=='月度收费'">
          <el-radio-group v-model="form.period">
            <el-radio value="1">月份</el-radio>
            <el-radio value="2">日期</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="月份" prop="monthInfo" v-if="billingType=='月度收费' && form.period==1">
          <el-checkbox-group v-model="form.monthInfo">
            <el-checkbox
                v-for="(item,index) in 12"
                :key="index"
                :label="item">
              {{ item }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="开始日期" prop="startDate" v-if="billingType=='月度收费' && form.period==2">
          <el-cascader
              v-model="form.startDate"
              :options="dateOptions"
              :props="cascaderProps"
              placeholder="请选择月份和日期"
              clearable
          />
          <div style="margin: 0 5px">至</div>
          <el-cascader
              v-model="form.endDate"
              :options="dateOptions"
              :props="cascaderProps"
              placeholder="请选择月份和日期"
              clearable
          />
        </el-form-item>
        <el-form-item label="请假收费方式" prop="leaveFeeMethod" v-if="billingType=='月度收费'">
          <el-radio-group v-model="form.leaveFeeMethod">
            <el-radio value="1">正常收费</el-radio>
            <el-radio value="2">退费</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="外出当天" prop="ifChargeGoOut" v-if="billingType=='月度收费' && form.leaveFeeMethod==2">
          <el-radio-group v-model="form.ifChargeGoOut">
            <el-radio value="1">收费</el-radio>
            <el-radio value="2">退费</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="回归当天" prop="ifChargeRegression"
                      v-if="billingType=='月度收费' && form.leaveFeeMethod==2">
          <el-radio-group v-model="form.ifChargeRegression">
            <el-radio value="1">收费</el-radio>
            <el-radio value="2">退费</el-radio>
          </el-radio-group>
        </el-form-item>
        <div style="margin: 0 20px;display: flex;align-items: center"
             v-if="billingType=='月度收费' && form.leaveFeeMethod==2">
          <div style="width: 120px">累计请假小于</div>
          <el-input type="number" max="31" v-model="form.minDayRefund" placeholder="0" style="width: 100px;"
                    @blur="form.maxDayRefund = form.minDayRefund"/>
          <text style="margin-left: 5px;margin-right: 20px">天，退费</text>
          <el-radio-group v-model="form.minDayType" @change="chooseMin">
            <el-radio value="1">对应天数</el-radio>
            <el-radio value="2">
              <el-input type="number" max="31" :disabled="form.minDayType!=2" v-model="form.minDayCost" placeholder="0"
                        style="width: 100px;"/>
              天
            </el-radio>
          </el-radio-group>
        </div>
        <div style="margin: 10px 20px;display: flex;align-items: center"
             v-if="billingType=='月度收费' && form.leaveFeeMethod==2">
          <div style="width: 120px">累计请假大于等于</div>
          <el-input type="number" max="31" v-model="form.maxDayRefund" placeholder="0" style="width: 100px;"
                    @blur="form.minDayRefund = form.maxDayRefund"/>
          <text style="margin-left: 5px;margin-right: 20px">天，退费</text>
          <el-radio-group v-model="form.maxDayType" @change="chooseMax">
            <el-radio value="1">对应天数</el-radio>
            <el-radio value="2">
              <el-input type="number" max="31" :disabled="form.maxDayType!=2" v-model="form.maxDayCost" placeholder="0"
                        style="width: 100px;"/>
              天
            </el-radio>
          </el-radio-group>
        </div>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ChargedItems">
import {
  listChargedItems,
  getChargedItems,
  delChargedItems,
  addChargedItems,
  updateChargedItems
} from "@/views/record/costSetting/api/chargedItems";
import {listAllChargedItemsType} from "@/views/record/costSetting/api/chargedItemsType.js";

const {proxy} = getCurrentInstance();
const {billing_type} = proxy.useDict('billing_type');

const chargedItemsList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const typeList = ref([]);
const billingType = ref('一次性收费');// 级联选择器配置
const cascaderProps = {
  value: 'value',
  label: 'label',
  children: 'children',
  emitPath: true, // 返回完整路径 [month, day]
  expandTrigger: 'hover'
}

// 生成月份和日期的级联选项
const dateOptions = computed(() => {
  const options = []
  const currentYear = new Date().getFullYear()

  // 生成12个月份
  for (let month = 1; month <= 12; month++) {
    const daysInMonth = new Date(currentYear, month, 0).getDate()
    const children = []

    // 为每个月生成对应的天数
    for (let day = 1; day <= daysInMonth; day++) {
      children.push({
        value: day,
        label: day + '日'
      })
    }

    options.push({
      value: month,
      label: month + '月',
      children: children
    })
  }

  return options
})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    projectName: null,
    typeId: null,
    ifCheckInFee: null,
    monthlyFeeStandard: null,
    dailyChargesStandard: null,
    period: null,
    monthInfo: null,
    startDate: null,
    endDate: null,
    price: null,
    unit: null,
    leaveFeeMethod: null,
    ifChargeGoOut: null,
    ifChargeRegression: null,
    minDayRefund: null,
    minDayCost: null,
    maxDayRefund: null,
    maxDayCost: null,
    remark: null,
  },
  rules: {
    projectName: [
      {required: true, message: "收费项目名称：必填不能为空", trigger: "blur"}
    ],
    typeId: [
      {required: true, message: "收费项目类型id：必填不能为空", trigger: "blur"}
    ],
    price: [
      {required: true, message: "价格不能为空", trigger: "blur"}
    ],
  }
});

const {queryParams, form, rules} = toRefs(data);

getList();
getTypeList();

function chooseMax(val) {
  if (val == 1) {
    form.value.maxDayCost = 0;
  }
}

function chooseMin(val) {
  if (val == 1) {
    form.value.minDayCost = 0;
  }
}

/** 选择项目类型 */
function handleChange(val) {
  let item = typeList.value.find(item => item.id == val)
  if (item) billingType.value = item.billingType;
}

/** 查询收费项目类型列表 */
function getTypeList() {
  listAllChargedItemsType().then(response => {
    typeList.value = response.data;
  });
}

/** 查询收费项目列表 */
function getList() {
  loading.value = true;
  listChargedItems(queryParams.value).then(response => {
    chargedItemsList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    projectName: null,
    typeId: null,
    ifCheckInFee: null,
    monthlyFeeStandard: null,
    dailyChargesStandard: null,
    period: '1',
    monthInfo: [],
    startDate: null,
    endDate: null,
    price: null,
    unit: null,
    leaveFeeMethod: null,
    ifChargeGoOut: null,
    ifChargeRegression: null,
    minDayRefund: null,
    minDayCost: null,
    maxDayRefund: null,
    maxDayCost: null,
    remark: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    deleteStatus: "0"
  };
  proxy.resetForm("chargedItemsRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加收费项目";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getChargedItems(_id).then(response => {
    form.value = response.data;
    if (form.value.monthInfo) form.value.monthInfo = form.value.monthInfo.split(",");
    if (form.value.startDate) form.value.startDate = JSON.parse(form.value.startDate);
    if (form.value.endDate) form.value.endDate = JSON.parse(form.value.endDate);
    open.value = true;
    title.value = "修改收费项目";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["chargedItemsRef"].validate(valid => {
    if (valid) {
      if (form.value.monthInfo) form.value.monthInfo = form.value.monthInfo.join(",");
      if (form.value.startDate) form.value.startDate = JSON.stringify(form.value.startDate)
      if (form.value.endDate) form.value.endDate = JSON.stringify(form.value.endDate)
      if (form.value.id != null) {
        updateChargedItems(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addChargedItems(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除收费项目编号为"' + _ids + '"的数据项？').then(function () {
    return delChargedItems(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('pg/chargedItems/export', {
    ...queryParams.value
  }, `chargedItems_${new Date().getTime()}.xlsx`)
}
</script>
